<?php
namespace App\Http\Controllers;

use App\Http\Model\Gift;
use App\Http\Model\HopeLuckDraw;
use App\Http\Model\LuckDraw;
use App\Http\Model\WishDefender;
use App\Http\Model\WishWheel;
use App\Http\Services\LuckDrawServices;
use App\Http\Services\WishDefenderServices;
use Illuminate\Http\Request;
use App\Lib\Response;
use App\Http\Model\Hint;
use App\Http\Services\UserServices;
use App\Http\Services\GameServices;
use Illuminate\Support\Facades\Redis;

class ApiGameController extends BaseController
{
    protected $userService;
    protected $gameService;
    protected $luckDrawService;
    protected $luckDrawModel;
    protected $hopeDrawModel;
    protected $giftModel;
    protected $wishWheelModel;
    protected $wishDefenderService;
    protected $wishDefenderModel;


    public function __construct(){
        $this->userService = new UserServices();
        $this->gameService = new GameServices();
        $this->luckDrawService = new LuckDrawServices();
        $this->luckDrawModel = new LuckDraw();
        $this->hopeDrawModel = new HopeLuckDraw();
        $this->giftModel = new Gift();
        $this->wishWheelModel = new WishWheel();
        $this->wishDefenderService = new WishDefenderServices();
        $this->wishDefenderModel = new WishDefender();
    }

    /**
     * 回调根据code获取sstoken
     */
    public function get_sstoken(Request $request){
        $result = [
            //错误码，0:成功，其他表示错误
            'ret_code' => 0,
            //错误信息
            'ret_msg' => (string) '',
            //data数据
            'data' => [
                //token
                'ss_token' => (string) '',
                //过期时间（毫秒数）
                'expire_date' => (int) 0,
                //userInfoObj对象，当userInfoObj对象有数据时，小游戏服务端会采用该数据，不会调用getUserinfo接口，节省一次调用
                'user_info' => [
                    //用户id
                    'uid' => (string) '',
                    //用户昵称
                    'nick_name' => (string) '',
                    //用户头像url(建议使用128*128尺寸)
                    'avatar_url' => (string) '',
                    //性别（female or male or "") 未知性别请填写空字符串
                    'gender' => (string) '',
                    //0:普通用户，1:机器人（默认为0）
                    'is_ai' => (int) 0,
                ]
            ],
        ];
        do {
            $userId = (int) $request->input('code');
            if(empty($userId)) {
                $result['ret_code'] = 1001;
                $result['ret_msg'] = '请求参数未传递';
            }
            //获取用户信息
            $userInfo = $this->userService->getResponseData($userId);
            if(empty($userInfo)) {
                $result['ret_code'] = 1002;
                $result['ret_msg'] = '用户不存在';
            }
            $gender = '';
            if($userInfo['gender'] == 1) {
                $gender = 'male';
            }
            if($userInfo['gender'] == 2) {
                $gender = 'female';
            }
            $result['data']['ss_token'] = $userInfo['user_id'].'.'.$userInfo['user_uid'].'.'.md5(json_encode($userInfo));
            $result['data']['expire_date'] = (time()+86400) * 1000;
            $result['data']['user_info']['uid'] = (string) $userInfo['user_id'];
            $result['data']['user_info']['nick_name'] = (string) $userInfo['nickname'];
            $result['data']['user_info']['avatar_url'] = (string) $userInfo['images'][0];
            $result['data']['user_info']['gender'] = $gender;

        } while (false);

        $jsonStr = json_encode($result,JSON_UNESCAPED_UNICODE);
        echo $jsonStr;
        exit;
    }

    /**
     * 回调更新sstoken
     */
    public function update_sstoken(Request $request){
        $result = [
            //错误码，0:成功，其他表示错误
            'ret_code' => 0,
            //错误信息
            'ret_msg' => (string) '',
            //data数据
            'data' => [
                //token
                'ss_token' => (string) '',
                //过期时间（毫秒数）
                'expire_date' => (int) 0
            ],
        ];
        do {
            write_log('gamecallback', 'update_sstoken', $request->all());

            $ss_token = (string) $request->input('ss_token');
            if(empty($ss_token)) {
                $result['ret_code'] = 1001;
                $result['ret_msg'] = '请求参数未传递';
            }
            $ss_token = explode('.', $ss_token);
            if(empty($ss_token[0])) {
                $result['ret_code'] = 1002;
                $result['ret_msg'] = '请求参数异常';
            }
            $userId = (int) $ss_token[0];
            if(empty($userId)) {
                $result['ret_code'] = 1003;
                $result['ret_msg'] = '请求参数未传递';
            }
            //获取用户信息
            $userInfo = $this->userService->getResponseData($userId);
            if(empty($userInfo)) {
                $result['ret_code'] = 1004;
                $result['ret_msg'] = '用户不存在';
            }
            $result['data']['ss_token'] = $userInfo['user_id'].'.'.$userInfo['user_uid'].'.'.md5(json_encode($userInfo));
            $result['data']['expire_date'] = (time()+86400) * 1000;

        } while (false);

        $jsonStr = json_encode($result,JSON_UNESCAPED_UNICODE);
        echo $jsonStr;
        exit;
    }

    /**
     * 回调获取用户信息
     */
    public function get_user_info(Request $request){
        $result = [
            //错误码，0:成功，其他表示错误
            'ret_code' => 0,
            //错误信息
            'ret_msg' => (string) '',
            //data数据
            'data' => [
                //用户id
                'uid' => (string) '',
                //用户昵称
                'nick_name' => (string) '',
                //用户头像url(建议使用128*128尺寸)
                'avatar_url' => (string) '',
                //性别（female or male or "") 未知性别请填写空字符串
                'gender' => (string) '',
                //0:普通用户，1:机器人（默认为0）
                'is_ai' => (int) 0,
            ],
        ];
        do {
            write_log('gamecallback', 'update_sstoken', $request->all());

            $ss_token = (string) $request->input('ss_token');
            if(empty($ss_token)) {
                $result['ret_code'] = 1001;
                $result['ret_msg'] = '请求参数未传递';
            }
            $ss_token = explode('.', $ss_token);
            if(empty($ss_token[0])) {
                $result['ret_code'] = 1002;
                $result['ret_msg'] = '请求参数异常';
            }
            $userId = (int) $ss_token[0];
            if(empty($userId)) {
                $result['ret_code'] = 1003;
                $result['ret_msg'] = '请求参数未传递';
            }
            //获取用户信息
            $userInfo = $this->userService->getResponseData($userId);
            if(empty($userInfo)) {
                $result['ret_code'] = 1004;
                $result['ret_msg'] = '用户不存在';
            }
            $gender = '';
            if($userInfo['gender'] == 1) {
                $gender = 'male';
            }
            if($userInfo['gender'] == 2) {
                $gender = 'female';
            }
            $result['data']['uid'] = (string) $userInfo['user_id'];
            $result['data']['nick_name'] = $userInfo['nickname'];
            $result['data']['avatar_url'] = $userInfo['images'][0];
            $result['data']['gender'] = $gender;

        } while (false);

        $jsonStr = json_encode($result,JSON_UNESCAPED_UNICODE);
        echo $jsonStr;
        exit;
    }

    /**
     * 回调游戏服务端上报游戏接入方的游戏的数据
     */
    public function report_game_info(Request $request){
        $result = [
            //错误码，0:成功，其他表示错误
            'ret_code' => 0,
            //错误信息
            'ret_msg' => (string) '',
        ];
        do {
            $data = $request->all();
            write_log('gamecallback', 'report_game_info', $data);
            if(!empty($data['report_type']) || empty($data['report_msg']['game_round_id'])) {
                $this->gameService->reportGameInfo($data);
            }
        } while (false);

        $jsonStr = json_encode($result,JSON_UNESCAPED_UNICODE);
        echo $jsonStr;
        exit;
    }

    /**
     * 游戏开始
     */
    public function gameStart(Request $request)
    {
        $user = $this->userService->get_current_user();
        if (empty($user)) {
            Response::returnResult(Hint::LOGIN_OUT);
            return;
        }
        $userId = $user['user_id'];

        $room_id = (int) $request->input("room_id");//房间ID
        $game_type = (int) $request->input("game_type");//游戏类型 2=你说我猜 3=飞行棋 4=数字炸弹
        $ai_num = (int) $request->input("ai_num");//添加机器人数量

        $data = $this->gameService->gameStart($userId, $room_id, $game_type, $ai_num);
        if($data['code'] != Hint::SUCCESS) {
            Response::returnResult($data['code'], $data['data'], $data['msg']);
        }
        Response::returnResult(Hint::SUCCESS, $data['data']);
    }

    /**
     * 游戏结束
     */
    public function gameEnd(Request $request)
    {
        $user = $this->userService->get_current_user();
        if (empty($user)) {
            Response::returnResult(Hint::LOGIN_OUT);
            return;
        }
        $userId = $user['user_id'];

        $room_id = (int) $request->input("room_id");//房间ID

        $data = $this->gameService->gameEnd($userId, $room_id);
        if($data['code'] != Hint::SUCCESS) {
            Response::returnResult($data['code'], $data['data'], $data['msg']);
        }
        Response::returnResult(Hint::SUCCESS, $data);
    }

    /**
     * 开启房间团战
     */
    public function roomPkOpen(Request $request)
    {
        $user = $this->userService->get_current_user();
        if (empty($user)) {
            Response::returnResult(Hint::LOGIN_OUT);
        }
        $userId = $user['user_id'];

        $room_id = (int) $request->input("room_id");//房间ID
        $battle_duration = (int) $request->input("battle_duration");//团战时间（秒）
        $team_name_1 = (string) $request->input("team_name_1");//队伍1名称
        $team_name_2 = (string) $request->input("team_name_2");//队伍2名称
        if(empty($room_id) || empty($battle_duration)) {
            Response::returnResult(Hint::PARAM_ERROR);
        }

        $data = $this->gameService->roomPkOpen($userId, $room_id, $battle_duration, $team_name_1, $team_name_2);
        if($data['code'] != Hint::SUCCESS) {
            Response::returnResult($data['code'], $data['data'], $data['msg']);
        }
        Response::returnResult(Hint::SUCCESS, $data['data']);
    }

    /**
     * 开始房间团战
     */
    public function roomPkStart(Request $request)
    {
        $user = $this->userService->get_current_user();
        if (empty($user)) {
            Response::returnResult(Hint::LOGIN_OUT);
            return;
        }
        $userId = $user['user_id'];
        $room_id = (int) $request->input("room_id");//房间ID
        if(empty($room_id)) {
            Response::returnResult(Hint::PARAM_ERROR);
        }

        $data = $this->gameService->roomPkStart($userId, $room_id);
        if($data['code'] != Hint::SUCCESS) {
            Response::returnResult($data['code'], $data['data'], $data['msg']);
        }
        Response::returnResult(Hint::SUCCESS, $data['data']);
    }

    /**
     * 结束房间团战
     */
    public function roomPkEnd(Request $request)
    {
        $user = $this->userService->get_current_user();
        if (empty($user)) {
            Response::returnResult(Hint::LOGIN_OUT);
            return;
        }
        $userId = $user['user_id'];

        $room_id = (int) $request->input("room_id");//房间ID

        $data = $this->gameService->roomPkEnd($userId, $room_id);
        if($data['code'] != Hint::SUCCESS) {
            Response::returnResult($data['code'], $data['data'], $data['msg']);
        }
        Response::returnResult(Hint::SUCCESS, $data['data']);
    }

    /**
     * 房间团战详情
     */
    public function roomPkInfo(Request $request)
    {
        $user = $this->userService->get_current_user();
        if (empty($user)) {
            Response::returnResult(Hint::LOGIN_OUT);
            return;
        }
        $userId = $user['user_id'];

        $room_id = (int) $request->input("room_id");//房间ID

        $data = $this->gameService->roomPkInfo($userId, $room_id);
        if($data['code'] != Hint::SUCCESS) {
            Response::returnResult($data['code'], $data['data'], $data['msg']);
        }
        Response::returnResult(Hint::SUCCESS, $data['data']);
    }


    public function poolList(Request $request)
    {
        $pool_id = (int) $request->input('game_id');
        $pool_level = (int) $request->input('game_level', 1000);
        $gift_price = (int) $request->input('gift_price', 100);
        $userId = (int) $request->input('user_id');
        if(empty($pool_id) || empty($userId)) {
            $this->returnRet(Hint::PARAM_ERROR);
        }

        $code = Hint::SUCCESS;
        $data = [];

        try {
            do {
                if ($pool_id == 1) {
                    $luckId = ($pool_level == 1001) ? 1001: 1000;
                    // 金蛋
                    $pool = $this->luckDrawModel->getWishLuckPool($luckId);
                    $basePoolList = []; //普通池的
                    $userPoolList = []; //用户个人池的
                    foreach ($pool as $val) {
                        if ($val['status'] != 1) {
                            continue;
                        }
                        //奖池配置数据
                        $poolConfig = $this->luckDrawModel->getWishLuckPoolConfig($val['id']);
                        if (empty($poolConfig)) {
                            continue;
                        }
                        $val['poolConfig'] = $poolConfig;

                        //普通池
                        if ($val['pool_type'] == 1) {
                            $basePoolList[] = $val;
                        }
                        //用户个人池
                        if (in_array($val['pool_type'], [2, 3])) {
                            if (!empty($poolUser) && !empty($poolUser['pool_id']) && $val['id'] == $poolUser['pool_id']) {
                                $userPoolList[] = $val;
                            }
                        }
                    }

                    $ifdrawInUserPool = 0; //是否在个人池抽奖 0=否 1=是
                    if (!empty($poolUser) && !empty($userPoolList)) {
                        $poolList = $userPoolList;
                        $ifdrawInUserPool = 1;
                    } else {
                        $poolList = $basePoolList;
                    }

                    if (empty($poolList)) {
                        $code = Hint::WAIT_OPEN;
                        break;
                    }

                    $giftToItemNo = array_column($poolList[0]['poolConfig'], 'gift_id', 'item_no');
//                var_dump($poolList[0]['poolConfig']);
//                var_dump($giftToItemNo);exit();

                    //用户总抽奖记录数
                    if ($ifdrawInUserPool) {
                        //个人池用户
                        $drawNumNow = $drawNum = $poolUser['draw_num'];
                    } else {
                        //普通
                        $drawNumNow = $drawNum = $this->luckDrawModel->getUserWishLuckDrawNumByWeek($userId, $luckId);
                    }

                    $data['draw_num'] = $drawNumNow;

                    $usePool = []; //使用的奖池
                    //在范围的
                    foreach ($poolList as $val) {
                        if ($val['min_num'] <= $drawNumNow && $drawNumNow <= $val['max_num']) {
                            $usePool = $val;
                        }
                    }
                    //上一个
                    $prevNum = 0;
                    if (empty($usePool)) {
                        foreach ($poolList as $val) {
                            if ($val['max_num'] <= $drawNumNow && $prevNum <= $val['max_num']) {
                                $usePool = $val;
                                $prevNum = $val['max_num'];
                            }
                        }
                    }
                    //下一个
                    $nextNum = 0;
                    if (empty($usePool)) {
                        foreach ($poolList as $val) {
                            if ($val['min_num'] >= $drawNumNow && ($nextNum == 0 || $nextNum >= $val['min_num'])) {
                                $usePool = $val;
                                $nextNum = $val['min_num'];
                            }
                        }
                    }
                    //还是没有取第一个
                    if (empty($usePool)) {
                        $usePool = $poolList[0];
                    }

                    //奖池礼物对应的奖池序号
//                $giftToItemNo = array_column($usePool['poolConfig'], 'gift_id', 'item_no');

                    //抽取
                    if (in_array($usePool['pool_type'], [2, 3])) {
                        //个人池
                        $poolKey = sprintf($this->luckDrawModel->wishLuckSelfPoolDataKey, $luckId ,$userId, $usePool['id']) . ":ALIAS:KEYNAME";
                    } else {
                        //普通
                        $poolKey = sprintf($this->luckDrawModel->wishLuckPoolDataKey, $luckId, $usePool['id']) . ":ALIAS:KEYNAME";
                    }

                } elseif ($pool_id == 2) {
                    // 转盘
                    //个人池用户
                    $poolUser = $this->wishWheelModel->getWishWheelPoolUserId($userId);
                    //奖池
                    $pool = $this->wishWheelModel->getWishWheelPool();
                    $basePoolList = [];//普通池的
                    $userPoolList = [];//用户个人池的
                    foreach($pool as $val) {
                        if($val['status'] != 1){
                            continue;
                        }
                        //奖池配置数据
                        $poolConfig = $this->wishWheelModel->getWishWheelPoolConfig($val['id']);
                        if(empty($poolConfig)) {
                            continue;
                        }
                        $val['poolConfig'] = $poolConfig;
                        //普通池
                        if($val['pool_type'] == 1) {
                            $basePoolList[] = $val;
                        }
                        //用户个人池
                        if(in_array($val['pool_type'], [2,3])) {
                            if(!empty($poolUser) && !empty($poolUser['pool_id']) && $val['id']==$poolUser['pool_id']){
                                $userPoolList[] = $val;
                            }
                        }
                    }

                    $ifdrawInUserPool = 0;//是否在个人池抽奖 0=否 1=是
                    if(!empty($poolUser) && !empty($userPoolList)) {
                        $poolList = $userPoolList;
                        $ifdrawInUserPool = 1;
                    }else{
                        $poolList = $basePoolList;
                    }

                    if(empty($poolList)) {
                        $code = Hint::WAIT_OPEN;
                        break;
                    }

                    //用户总抽奖记录数
                    if($ifdrawInUserPool) {
                        //个人池用户
                        $drawNumNow = $drawNum = $poolUser['draw_num'];
                    }else{
                        //普通
                        $drawNumNow = $drawNum = $this->wishWheelModel->getUserWishWheelDrawNumByWeek($userId);
                    }

                    $usePool = [];//使用的奖池
                    //在范围的
                    foreach($poolList as $val) {
                        if($val['min_num']<=$drawNumNow && $drawNumNow<=$val['max_num']) {
                            $usePool = $val;
                        }
                    }
                    //上一个
                    $prevNum = 0;
                    if(empty($usePool)) {
                        foreach($poolList as $val) {
                            if($val['max_num']<=$drawNumNow && $prevNum<=$val['max_num']) {
                                $usePool = $val;
                                $prevNum = $val['max_num'];
                            }
                        }
                    }
                    //下一个
                    $nextNum = 0;
                    if(empty($usePool)) {
                        foreach($poolList as $val) {
                            if($val['min_num']>=$drawNumNow && ($nextNum==0 || $nextNum>=$val['min_num'])) {
                                $usePool = $val;
                                $nextNum = $val['min_num'];
                            }
                        }
                    }
                    //还是没有取第一个
                    if(empty($usePool)) {
                        $usePool = $poolList[0];
                    }

                    //奖池礼物对应的奖池序号
                    $giftToItemNo = array_column($usePool['poolConfig'], 'gift_id', 'item_no');

                    //抽取
                    if(in_array($usePool['pool_type'], [2,3])) {
                        //个人池
                        $poolKey = sprintf($this->wishWheelModel->wishWheelSelfPoolDataKey ,$userId, $usePool['id']) . ":ALIAS:KEYNAME";
                    }else{
                        //普通
                        $poolKey = sprintf($this->wishWheelModel->wishWheelPoolDataKey, $usePool['id']) . ":ALIAS:KEYNAME";
                    }

                } elseif ($pool_id == 3) {
                    // 万神殿
                    $luckId = $this->wishDefenderService->getLuckId();

                    //个人池用户
                    $poolUser = $this->wishDefenderModel->getPoolUser($userId, $luckId);

                    //奖池
                    $pool = $this->wishDefenderModel->getPool($luckId);
                    $basePoolList = []; //普通池的
                    $userPoolList = []; //用户个人池的
                    foreach ($pool as $val) {
                        if ($val['status'] != 1) {
                            continue;
                        }
                        //奖池配置数据
                        $poolConfig = $this->wishDefenderModel->getWishLuckPoolConfig($val['id']);
                        if (empty($poolConfig)) {
                            write_log('error_wishdefender', '$poolConfig empty', ['pool_id' => $val['id']]);
                            continue;
                        }
                        $val['poolConfig'] = $poolConfig;
                        //普通池
                        if ($val['pool_type'] == 1) {
                            $basePoolList[] = $val;
                        }
                        //用户个人池
                        if (in_array($val['pool_type'], [2, 3])) {
                            if (!empty($poolUser) && !empty($poolUser['pool_id']) && $val['id'] == $poolUser['pool_id']) {
                                $userPoolList[] = $val;
                            }
                        }
                    }

                    $ifdrawInUserPool = 0; //是否在个人池抽奖 0=否 1=是
                    if (!empty($poolUser) && !empty($userPoolList)) {
                        $poolList = $userPoolList;
                        $ifdrawInUserPool = 1;
                    } else {
                        $poolList = $basePoolList;
                    }
                    if (empty($poolList)) {
                        $code = Hint::WAIT_OPEN;
                        break;
                    }

                    //用户总抽奖记录数
                    if ($ifdrawInUserPool) {
                        //个人池用户
                        $drawNumNow = $drawNum = $poolUser['draw_num'];
                    } else {
                        //普通
                        $drawNumNow = $drawNum = $this->wishDefenderModel->getUserWishLuckDrawNumByWeek($userId, $luckId);
                    }

                    $usePool = []; //使用的奖池
                    //在范围的
                    foreach ($poolList as $val) {
                        if ($val['min_num'] <= $drawNumNow && $drawNumNow <= $val['max_num']) {
                            $usePool = $val;
                        }
                    }
                    //上一个
                    $prevNum = 0;
                    if (empty($usePool)) {
                        foreach ($poolList as $val) {
                            if ($val['max_num'] <= $drawNumNow && $prevNum <= $val['max_num']) {
                                $usePool = $val;
                                $prevNum = $val['max_num'];
                            }
                        }
                    }
                    //下一个
                    $nextNum = 0;
                    if (empty($usePool)) {
                        foreach ($poolList as $val) {
                            if ($val['min_num'] >= $drawNumNow && ($nextNum == 0 || $nextNum >= $val['min_num'])) {
                                $usePool = $val;
                                $nextNum = $val['min_num'];
                            }
                        }
                    }
                    //还是没有取第一个
                    if (empty($usePool)) {
                        $usePool = $poolList[0];
                    }

                    //奖池礼物对应的奖池序号
                    $giftToItemNo = array_column($usePool['poolConfig'], 'gift_id', 'item_no');

                    //抽取
                    if (in_array($usePool['pool_type'], [2, 3])) {
                        //个人池
                        $poolKey = sprintf($this->wishDefenderModel->wishLuckSelfPoolDataKey, $luckId, $userId, $usePool['id']) . ":ALIAS:KEYNAME";
                    } else {
                        //普通
                        $poolKey = sprintf($this->wishDefenderModel->wishLuckPoolDataKey, $luckId, $usePool['id']) . ":ALIAS:KEYNAME";
                    }

                } elseif ($pool_id == 4) {
                    // 幸运礼物
                    $pool = $this->giftModel->getLuckGiftPool();
                    $poolList = [];//已开启的奖池
                    foreach($pool as $val) {
                        if($val['gift_price'] != $gift_price) {
                            continue;
                        }
                        if($val['status'] == 1){
                            $poolList[] = $val;
                        }
                    }
                    $list = [];

                    if ($poolList) {
                        //用户总消耗钻石数
                        $diamondNumNow = $diamondNum = $this->giftModel->getUserLuckGiftDiamondNumByWeek($userId);
                        $usePool = [];//使用的奖池
                        //在范围的
                        foreach($poolList as $val) {
                            if($val['min_num']<=$diamondNumNow && $diamondNumNow<=$val['max_num']) {
                                $usePool = $val;
                            }
                        }
                        //上一个
                        $prevNum = 0;
                        if(empty($usePool)) {
                            foreach($poolList as $val) {
                                if($val['max_num']<=$diamondNumNow && $prevNum<=$val['max_num']) {
                                    $usePool = $val;
                                    $prevNum = $val['max_num'];
                                }
                            }
                        }
                        //下一个
                        $nextNum = 0;
                        if(empty($usePool)) {
                            foreach($poolList as $val) {
                                if($val['min_num']>=$diamondNumNow && ($nextNum==0 || $nextNum>=$val['min_num'])) {
                                    $usePool = $val;
                                    $nextNum = $val['min_num'];
                                }
                            }
                        }
                        //还是没有取第一个
                        if(empty($usePool)) {
                            $usePool = $poolList[0];
                        }

                        $poolKey = sprintf($this->giftModel->luckGiftPoolDataKey, $usePool['id']) . ":ALIAS:KEYNAME";
                        $valKey = Redis::GET($poolKey);
                        $head = Redis::LRANGE($valKey, 0, 200);
                        $tail = Redis::LRANGE($valKey, -200, -1);
                        $list = array_merge($head, $tail);
                    }

                    $data['list'] = $list;
                    $this->returnRet($code, $data);

                } elseif ($pool_id == 5) {
                    // 心心相印
                    //获取用户当前抽奖的奖池
                    //奖池
                    $pool = $this->hopeDrawModel->getWishLuckPool();
                    $basePoolList = []; //普通池的
                    $userPoolList = []; //用户个人池的
                    foreach ($pool as $val) {
                        if ($val['status'] != 1) {
                            continue;
                        }
                        //奖池配置数据
                        $poolConfig = $this->hopeDrawModel->getWishLuckPoolConfig($val['id']);
                        if (empty($poolConfig)) {
                            continue;
                        }
                        $val['poolConfig'] = $poolConfig;
                        //普通池
                        if ($val['pool_type'] == 1) {
                            $basePoolList[] = $val;
                        }
                        //用户个人池
                        if (in_array($val['pool_type'], [2, 3])) {
                            if (!empty($poolUser) && !empty($poolUser['pool_id']) && $val['id'] == $poolUser['pool_id']) {
                                $userPoolList[] = $val;
                            }
                        }
                    }
                    $poolList = []; //已开启的奖池
                    $giftToItemNo = []; //奖池礼物对应的奖池序号
                    $ifdrawInUserPool = 0; //是否在个人池抽奖 0=否 1=是
                    if (!empty($poolUser) && !empty($userPoolList)) {
                        $poolList = $userPoolList;
                        $ifdrawInUserPool = 1;
                    } else {
                        $poolList = $basePoolList;
                    }
                    if (empty($poolList)) {
                        $code = Hint::WAIT_OPEN;
                        break;
                    }

                    //用户总抽奖记录数
                    if ($ifdrawInUserPool) {
                        //个人池用户
                        $drawNumNow = $drawNum = $poolUser['draw_num'];
                    } else {
                        //普通
                        $drawNumNow = $drawNum = $this->hopeDrawModel->getDrawCountByThreeDays($userId);
                    }

                    $usePool = []; //使用的奖池
                    //在范围的
                    foreach ($poolList as $val) {
                        if ($val['min_num'] <= $drawNumNow && $drawNumNow <= $val['max_num']) {
                            $usePool = $val;
                        }
                    }
                    //上一个
                    $prevNum = 0;
                    if (empty($usePool)) {
                        foreach ($poolList as $val) {
                            if ($val['max_num'] <= $drawNumNow && $prevNum <= $val['max_num']) {
                                $usePool = $val;
                                $prevNum = $val['max_num'];
                            }
                        }
                    }
                    //下一个
                    $nextNum = 0;
                    if (empty($usePool)) {
                        foreach ($poolList as $val) {
                            if ($val['min_num'] >= $drawNumNow && ($nextNum == 0 || $nextNum >= $val['min_num'])) {
                                $usePool = $val;
                                $nextNum = $val['min_num'];
                            }
                        }
                    }
                    //还是没有取第一个
                    if (empty($usePool)) {
                        $usePool = $poolList[0];
                    }

                    //抽取
                    if (in_array($usePool['pool_type'], [2, 3])) {
                        //个人池
                        $poolKey = sprintf($this->hopeDrawModel->wishLuckSelfPoolDataKey, $userId, $usePool['id']) . ":ALIAS:KEYNAME";
                    } else {
                        //普通
                        $poolKey = sprintf($this->hopeDrawModel->wishLuckPoolDataKey, $usePool['id']) . ":ALIAS:KEYNAME";
                    }

                }
                else {
                    $code = Hint::PARAM_ERROR;
                    break;
                }

                $data['draw_num'] = $drawNumNow;

                $valKey = Redis::GET($poolKey);
                $itemNoList1 = Redis::LRANGE($valKey, 0, 200);
                $itemNoList2 = Redis::LRANGE($valKey, -200, -1);
                $itemNoList = array_merge($itemNoList1, $itemNoList2);

                $poolConfigMap = array_column($usePool['poolConfig'], null, 'id');

                $itemNoGiftList = [];
                foreach ($itemNoList as $key => $poolConfigId) {
                    $itemNoGiftList[] = [
                        'item_no' => $poolConfigMap[$poolConfigId]['item_no'],
                        'gift_id' => $poolConfigMap[$poolConfigId]['gift_id'] ?? 0,
                    ];
                }

                $giftIds = array_column($itemNoGiftList, 'gift_id');
                $giftList = $this->giftModel->getGiftByGiftIds($giftIds, ['gift_id', 'name', 'price', 'image']);
                $giftMap = array_column($giftList, null, 'gift_id');

                foreach ($itemNoGiftList as $k => $val) {
                    $itemNoGiftList[$k]['name'] = isset($giftMap[$val['gift_id']]) ? $giftMap[$val['gift_id']]['name'] : '';
                    $itemNoGiftList[$k]['price'] = isset($giftMap[$val['gift_id']]) ? $giftMap[$val['gift_id']]['price'] :  0;
                }

                $data['list'] = $itemNoGiftList;

            } while (false);
        } catch (\Exception $e) {
            write_log('poolList', "poolList ERROR", ['msg' => $e->getMessage(), 'data' => $request->all()]);
            $code = Hint::ERROR;
        }

        $this->returnRet($code, $data);
    }

    /**
     * @desc 接口数据返回统一方法
     * */
    public function returnRet($code, $data = array(), $msg='', $aes=1)
    {
        // if ($code == -1){
        // header('HTTP/1.1 500 Internal Server Error');
        // }
        if(empty($msg)) {
            $msg = isset(Hint::$Msg[$code]) ? Hint::$Msg[$code] : '失败';
        }

        $res['code'] = $code;
        $res['msg'] = $msg;
        $res['data'] = $data;

        $jsonStr = json_encode($res,JSON_UNESCAPED_UNICODE);

        echo $jsonStr;
        exit;
    }

}
